package jnpf.permission.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.entity.ModuleEntity;
import jnpf.base.entity.SystemEntity;
import jnpf.base.model.form.ModuleFormModel;
import jnpf.base.service.ModuleService;
import jnpf.base.service.SystemService;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.base.UserInfo;
import jnpf.constant.MsgCode;
import jnpf.entity.LogEntity;
import jnpf.permission.constant.PermissionConst;
import jnpf.permission.entity.*;
import jnpf.base.model.button.ButtonModel;
import jnpf.base.model.column.ColumnModel;
import jnpf.base.model.module.ModuleModel;
import jnpf.base.model.resource.ResourceModel;
import jnpf.model.UserLogForm;
import jnpf.permission.model.authorize.AuthorizeModel;
import jnpf.permission.model.authorize.AuthorizeVO;
import jnpf.permission.model.permission.PermissionModel;
import jnpf.permission.model.user.form.*;
import jnpf.permission.model.user.mod.UserAuthorizeModel;
import jnpf.permission.model.user.vo.UserAuthorizeVO;
import jnpf.permission.model.user.vo.UserBaseInfoVO;
import jnpf.permission.model.user.vo.UserLogVO;
import jnpf.permission.model.user.vo.UserSubordinateVO;
import jnpf.permission.service.*;
import jnpf.permission.util.PermissionUtil;
import jnpf.service.LogService;
import jnpf.util.*;
import jnpf.util.JsonUtil;
import jnpf.util.treeutil.ListToTreeUtil;
import jnpf.util.treeutil.SumTree;
import jnpf.util.treeutil.newtreeutil.TreeDotUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 个人资料
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月26日 上午9:18
 */
@Api(tags = "个人资料", value = "CurrentUsersInfo")
@RestController
@RequestMapping("/api/permission/Users/Current")
public class UserSettingController {

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private UserService userService;
    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private LogService logService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PositionService positionService;
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private CacheKeyUtil cacheKeyUtil;
    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private OrganizeRelationService organizeRelationService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private ModuleService moduleService;


    /**
     * 我的信息
     *
     * @return
     */
    @ApiOperation("个人资料")
    @GetMapping("/BaseInfo")
    public ActionResult<UserBaseInfoVO> get() {
        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = userService.getInfo(userInfo.getUserId());

        String catchKey = cacheKeyUtil.getAllUser();
        if (redisUtil.exists(catchKey)) {
            redisUtil.remove(catchKey);
        }

        UserBaseInfoVO vo = JsonUtil.getJsonToBean(userEntity, UserBaseInfoVO.class);


        if (StringUtil.isNotEmpty(userEntity.getManagerId())) {
            UserEntity menager = userService.getInfo(userEntity.getManagerId());
            vo.setManager(menager != null ? menager.getRealName() + "/" + menager.getAccount() : "");
        }

        //设置语言和主题
        vo.setLanguage(userEntity.getLanguage() != null ? userEntity.getLanguage() : "zh-CN");
        vo.setTheme(userEntity.getTheme() != null ? userEntity.getTheme() : "W-001");

        // 获取组织
        vo.setOrganize(PermissionUtil.getLinkInfoByOrgId(userInfo.getOrganizeId(), organizeService, false));

        // 获取角色
        if(StringUtil.isNotEmpty(userInfo.getOrganizeId())){
            vo.setRoleId(roleService.getCurRolesByOrgId(userInfo.getOrganizeId()).stream()
                    .map(PermissionEntityBase::getFullName).collect(Collectors.joining(",")));
        }

        // 获取主要岗位
        List<PositionEntity> positionEntityList= positionService.getListByOrgIdAndUserId(userInfo.getOrganizeId(), userEntity.getId());
        if(positionEntityList.size() > 0){
            List<String> fullNames = positionEntityList.stream().map(PositionEntity::getFullName).collect(Collectors.toList());
            vo.setPosition(String.join(",", fullNames));
        }

        // 获取用户
        if (StringUtil.isNotEmpty(userInfo.getTenantId())) {
            vo.setAccount(userInfo.getTenantId() + "@" + vo.getAccount());
        }

        // 获取用户头像
        if (!StringUtil.isEmpty(userInfo.getUserIcon())) {
            vo.setAvatar(UploaderUtil.uploaderImg(userInfo.getUserIcon()));
        }
        vo.setBirthday(userEntity.getBirthday() != null ? userEntity.getBirthday().getTime() : null);
        return ActionResult.success(vo);
    }

    /**
     * 递归找他的上级
     */
    public void getOrganizeName(List<OrganizeEntity> OrganizeList, String OrganizeId, StringBuilder organizeName) {
        List<OrganizeEntity> OrganizeList2 = OrganizeList.stream().filter(t -> t.getId().equals(OrganizeId)).collect(Collectors.toList());
        if (OrganizeList2.size() > 0) {
            for (OrganizeEntity organizeEntity : OrganizeList2) {
                if ("-1".equals(organizeEntity.getParentId())) {
                    //父级为-1时候退出
                    organizeName.append(organizeEntity.getFullName());
                } else {
                    organizeName.append(organizeEntity.getFullName() + "/");
                }
            }
            for (OrganizeEntity orgSub : OrganizeList2) {
                getOrganizeName(OrganizeList, orgSub.getParentId(), organizeName);
            }
        }
    }


    /**
     * 我的权限
     *
     * @return
     */
    @ApiOperation("系统权限")
    @GetMapping("/Authorize")
    public ActionResult<UserAuthorizeVO> getList() {

        AuthorizeVO authorizeModel = authorizeService.getAuthorize(false);
        List<AuthorizeEntity> authorizeList = new ArrayList<>();
        //赋值图标
        Map<String, ModuleModel> moduleMap = this.moduleList(authorizeModel.getModuleList());
        List<ModuleModel> modelList = authorizeModel.getModuleList();
        UserInfo userInfo = userProvider.get();
        if (StringUtil.isEmpty(userInfo.getSystemId())) {
            SystemEntity systemEntity = systemService.getMainSystem();
            userInfo.setSystemId(systemEntity.getId());
        }
        modelList = modelList.stream().filter(t -> t != null && StringUtil.isNotEmpty(t.getSystemId()) && t.getSystemId().equals(userInfo.getSystemId())).collect(Collectors.toList());
        UserAuthorizeVO vo = UserAuthorizeVO.builder()
                .button(this.moduleButton(modelList, authorizeModel.getButtonList(), authorizeList, moduleMap))
                .column(this.moduleColumn(modelList, authorizeModel.getColumnList(), authorizeList, moduleMap))
                .form(this.moduleForm(modelList, authorizeModel.getFormsList(), authorizeList, moduleMap))
                .resource(this.resourceData(modelList, authorizeModel.getResourceList(), authorizeList, moduleMap))
                .module(this.module(modelList, authorizeList)).build();
        return ActionResult.success(vo);
    }

    /**
     * 系统日志
     *
     * @param userLogForm
     * @return
     */
    @ApiOperation("系统日志")
    @GetMapping("/SystemLog")
    public ActionResult<PageListVO<UserLogVO>> getLogList(UserLogForm userLogForm) {
        List<LogEntity> data = logService.getList(userLogForm);
        List<UserLogVO> list = JsonUtil.getJsonToList(data, UserLogVO.class);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setIpaddress(data.get(i).getIpAddress());
            list.get(i).setRequestURL(data.get(i).getRequestUrl());
        }
        PaginationVO paginationVO = JsonUtil.getJsonToBean(userLogForm, PaginationVO.class);
        return ActionResult.page(list, paginationVO);
    }

    /**
     * 修改用户资料
     *
     * @param userInfoForm
     * @return
     */
    @ApiOperation("修改用户资料")
    @PutMapping("/BaseInfo")
    public ActionResult updateInfo(@RequestBody UserInfoForm userInfoForm) throws Exception {
        UserEntity userEntity = userService.getInfo(userProvider.get().getUserId());
        userEntity.setBirthday(userInfoForm.getBirthday() == null ? null : new Date(userInfoForm.getBirthday()));
        userEntity.setCertificatesNumber(userInfoForm.getCertificatesNumber());
        userEntity.setCertificatesType(userInfoForm.getCertificatesType());
        userEntity.setEducation(userInfoForm.getEducation());
        userEntity.setEmail(userInfoForm.getEmail());
        userEntity.setGender(userInfoForm.getGender());
        userEntity.setLandline(userInfoForm.getLandline());
        userEntity.setMobilePhone(userInfoForm.getMobilePhone());
        userEntity.setNation(userInfoForm.getNation());
        userEntity.setNativePlace(userInfoForm.getNativePlace());
        userEntity.setPostalAddress(userInfoForm.getPostalAddress());
        userEntity.setRealName(userInfoForm.getRealName());
        userEntity.setSignature(userInfoForm.getSignature());
        userEntity.setTelePhone(userInfoForm.getTelePhone());
        userEntity.setUrgentContacts(userInfoForm.getUrgentContacts());
        userEntity.setUrgentTelePhone(userInfoForm.getUrgentTelePhone());
        userService.updateById(userEntity);
        return ActionResult.success(MsgCode.SU002.get());
    }

    /**
     * 修改用户密码
     *
     * @return
     */
    @ApiOperation("修改用户密码")
    @PostMapping("/Actions/ModifyPassword")
    public ActionResult modifyPassword(@RequestBody @Valid UserModifyPasswordForm userModifyPasswordForm) {
        UserEntity userEntity = userService.getInfo(userProvider.get().getUserId());
        if (userEntity != null) {
//            if ("1".equals(String.valueOf(userEntity.getIsAdministrator()))) {
//                return ActionResult.fail("无法修改管理员账户");
//            }
            String timestamp = String.valueOf(redisUtil.getString(userModifyPasswordForm.getTimestamp()));
            if (!userModifyPasswordForm.getCode().equalsIgnoreCase(timestamp)) {
                return ActionResult.fail(MsgCode.LOG104.get());
            }
            if (!Md5Util.getStringMd5((userModifyPasswordForm.getOldPassword().toLowerCase() + userEntity.getSecretkey().toLowerCase())).equals(userEntity.getPassword())) {
                return ActionResult.fail(MsgCode.LOG201.get());
            }
            userEntity.setPassword(userModifyPasswordForm.getPassword());
            userService.updatePassword(userEntity);
            userService.delCurUser(userEntity.getId());
            return ActionResult.success(MsgCode.LOG202.get());
        }
        return ActionResult.fail(MsgCode.LOG203.get());

    }

    /**
     * 我的下属
     *
     * @param
     * @return
     */
    @ApiOperation("我的下属")
    @GetMapping("/Subordinate/{id}")
    public ActionResult getSubordinate(@PathVariable("id") String id) {
        List<UserEntity> userName = new ArrayList<>(16);
        List<UserSubordinateVO> list = new ArrayList<>();
        if ("0".equals(id)) {
            if (Objects.isNull(userProvider.get()) || StringUtil.isEmpty(userProvider.get().getUserId())) {
                return ActionResult.success(list);
            }
            userName.add(userService.getInfo(userProvider.get().getUserId()));
        } else {
            userName = new ArrayList<>(userService.getListByManagerId(id, null));
        }
        List<String> department = userName.stream().map(t -> t.getOrganizeId()).collect(Collectors.toList());
        List<OrganizeEntity> departmentList = organizeService.getOrganizeName(department);
        for (UserEntity user : userName) {
            String departName = departmentList.stream().filter(
                    t -> String.valueOf(user.getOrganizeId()).equals(String.valueOf(t.getId()))
            ).findFirst().orElse(new OrganizeEntity()).getFullName();
            PositionEntity entity = null;
            if (StringUtil.isNotEmpty(user.getPositionId())) {
                String[] split = user.getPositionId().split(",");
                for (String positionId : split) {
                    entity = positionService.getInfo(positionId);
                    if (Objects.nonNull(entity)) {
                        break;
                    }
                }
            }
            UserSubordinateVO subordinateVO = UserSubordinateVO.builder()
                    .id(user.getId())
                    .avatar(UploaderUtil.uploaderImg(user.getHeadIcon()))
                    .department(departName)
                    .userName(user.getRealName() + "/" + user.getAccount())
                    .position(entity != null ? entity.getFullName() : null)
                    .isLeaf(false).build();
            list.add(subordinateVO);
        }
        return ActionResult.success(list);
    }

    /**
     * 修改系统主题
     *
     * @param userThemeForm
     * @return
     */
    @ApiOperation("修改系统主题")
    @PutMapping("/SystemTheme")
    public ActionResult updateTheme(@RequestBody @Valid UserThemeForm userThemeForm) {
        UserEntity entity = JsonUtil.getJsonToBean(userThemeForm, UserEntity.class);
        entity.setId(userProvider.get().getUserId());
        userService.updateById(entity);
        return ActionResult.success(MsgCode.SU016.get());
    }

    /**
     * 修改头像
     *
     * @return
     */
    @ApiOperation("修改头像")
    @PutMapping("/Avatar/{name}")
    public ActionResult updateAvatar(@PathVariable("name") String name) throws Exception {
        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = userService.getInfo(userInfo.getUserId());
        userEntity.setHeadIcon(name);
        userService.update(userEntity.getId(), userEntity);
        if (!StringUtil.isEmpty(userInfo.getId())) {
            userInfo.setUserIcon(name);
            //redisUtil.insert(userInfo.getId(), userInfo, DateUtil.getTime(userInfo.getOverdueTime()) - DateUtil.getTime(new Date()));
            UserProvider.setLoginUser(userInfo);
            UserProvider.setLocalLoginUser(userInfo);
        }
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 修改系统语言
     *
     * @param userLanguageForm
     * @return
     */
    @ApiOperation("修改系统语言")
    @PutMapping("/SystemLanguage")
    public ActionResult updateLanguage(@RequestBody @Valid UserLanguageForm userLanguageForm) {
        UserEntity userEntity = userService.getInfo(userProvider.get().getUserId());
        userEntity.setLanguage(userLanguageForm.getLanguage());
        userService.updateById(userEntity);
        return ActionResult.success(MsgCode.SU016.get());
    }


    /**
     * 赋值图标
     *
     * @param moduleList
     * @return
     */
    private Map<String, ModuleModel> moduleList(List<ModuleModel> moduleList) {
        Map<String, ModuleModel> auth = new HashMap<>(16);
        for (ModuleModel module : moduleList) {
            auth.put(module.getId(), module);
            module.setIcon(module.getIcon());
        }
        return auth;
    }

    /**
     * 功能权限
     *
     * @param moduleList    功能
     * @param authorizeLiat 权限集合
     * @return
     */
    private List<UserAuthorizeModel> module(List<ModuleModel> moduleList, List<AuthorizeEntity> authorizeLiat) {
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<AuthorizeModel> treeList = JsonUtil.getJsonToList(moduleList, AuthorizeModel.class);
        List<SumTree<AuthorizeModel>> trees = TreeDotUtils.convertListToTreeDot(treeList, "-1");
        List<UserAuthorizeModel> vo = JsonUtil.getJsonToList(trees, UserAuthorizeModel.class);
        List<UserAuthorizeModel> dataList = new LinkedList<>();
        List<UserAuthorizeModel> appChildList = new LinkedList<>();
        for (UserAuthorizeModel model : vo) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            UserAuthorizeModel appData = new UserAuthorizeModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
        }
        return dataList;
    }

    /**
     * 按钮权限
     *
     * @param moduleList       功能
     * @param moduleButtonList 按钮
     * @param authorizeLiat    权限集合
     * @return
     */
    private List<UserAuthorizeModel> moduleButton(List<ModuleModel> moduleList, List<ButtonModel> moduleButtonList, List<AuthorizeEntity> authorizeLiat, Map<String, ModuleModel> moduleMap) {
        List<AuthorizeModel> treeList = new ArrayList<>();
        Set<String> moduleModeId = new HashSet<>();
        //获取按钮的菜单id
        for (ButtonModel buttonModel : moduleButtonList) {
            moduleModeId.add(buttonModel.getModuleId());
            AuthorizeModel treeModel = new AuthorizeModel();
            treeModel.setId(buttonModel.getId());
            treeModel.setFullName(buttonModel.getFullName());
            treeModel.setParentId(buttonModel.getModuleId());
            treeModel.setIcon(buttonModel.getIcon());
            treeList.add(treeModel);
        }
        List<ModuleModel> buttonList = moduleList.stream().filter(t -> moduleModeId.contains(t.getId())).collect(Collectors.toList());
        List<AuthorizeModel> moduleListAll = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(buttonList, moduleList), AuthorizeModel.class);
        treeList.addAll(moduleListAll);
        treeList = treeList.stream().sorted(Comparator.comparing(AuthorizeModel::getSortCode)).collect(Collectors.toList());
        List<SumTree<AuthorizeModel>> trees = TreeDotUtils.convertListToTreeDot(treeList, "-1");
        //组装菜单树
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<UserAuthorizeModel> data = JsonUtil.getJsonToList(trees, UserAuthorizeModel.class);
        List<UserAuthorizeModel> dataList = new LinkedList<>();
        List<UserAuthorizeModel> appChildList = new LinkedList<>();
        for (UserAuthorizeModel model : data) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            UserAuthorizeModel appData = new UserAuthorizeModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
        }
        return dataList;
    }

    /**
     * 列表权限
     *
     * @param moduleList       功能
     * @param moduleColumnList 列表
     * @param authorizeLiat    权限集合
     * @return
     */
    private List<UserAuthorizeModel> moduleColumn(List<ModuleModel> moduleList, List<ColumnModel> moduleColumnList, List<AuthorizeEntity> authorizeLiat, Map<String, ModuleModel> moduleMap) {
        List<AuthorizeModel> treeList = new ArrayList<>();
        List<String> moduleModeId = new ArrayList<>();
        //获取按钮的菜单id
        for (ColumnModel columnModel : moduleColumnList) {
            moduleModeId.add(columnModel.getModuleId());
            AuthorizeModel treeModel = new AuthorizeModel();
            treeModel.setId(columnModel.getId());
            treeModel.setFullName(columnModel.getFullName());
            treeModel.setParentId(columnModel.getModuleId());
            treeModel.setIcon("fa fa-tags column");
            treeList.add(treeModel);
        }
        List<ModuleModel> buttonList = moduleList.stream().filter(t -> moduleModeId.contains(t.getId())).collect(Collectors.toList());
        List<AuthorizeModel> moduleListAll = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(buttonList, moduleList), AuthorizeModel.class);
        treeList.addAll(moduleListAll);
        treeList = treeList.stream().sorted(Comparator.comparing(AuthorizeModel::getSortCode)).collect(Collectors.toList());
        List<SumTree<AuthorizeModel>> trees = TreeDotUtils.convertListToTreeDot(treeList, "-1");
        //组装菜单树
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<UserAuthorizeModel> data = JsonUtil.getJsonToList(trees, UserAuthorizeModel.class);
        List<UserAuthorizeModel> dataList = new LinkedList<>();
        List<UserAuthorizeModel> appChildList = new LinkedList<>();
        for (UserAuthorizeModel model : data) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            UserAuthorizeModel appData = new UserAuthorizeModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
        }
        return dataList;
    }

    /**
     * 表单权限
     *
     * @param moduleList     功能
     * @param moduleFormList 表单
     * @param authorizeLiat  权限集合
     * @return ignore
     */
    private List<UserAuthorizeModel> moduleForm(List<ModuleModel> moduleList, List<ModuleFormModel> moduleFormList, List<AuthorizeEntity> authorizeLiat, Map<String, ModuleModel> moduleMap) {
        List<AuthorizeModel> treeList = new ArrayList<>();
        List<String> moduleModeId = new ArrayList<>();
        //获取按钮的菜单id
        for (ModuleFormModel formModel : moduleFormList) {
            moduleModeId.add(formModel.getModuleId());
            AuthorizeModel treeModel = new AuthorizeModel();
            treeModel.setId(formModel.getId());
            treeModel.setFullName(formModel.getFullName());
            treeModel.setParentId(formModel.getModuleId());
            treeModel.setIcon("fa fa-binoculars resource");
            treeList.add(treeModel);
        }
        List<ModuleModel> buttonList = moduleList.stream().filter(t -> moduleModeId.contains(t.getId())).collect(Collectors.toList());
        List<AuthorizeModel> moduleListAll = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(buttonList, moduleList), AuthorizeModel.class);
        treeList.addAll(moduleListAll);
        treeList = treeList.stream().sorted(Comparator.comparing(AuthorizeModel::getSortCode)).collect(Collectors.toList());
        List<SumTree<AuthorizeModel>> trees = TreeDotUtils.convertListToTreeDot(treeList, "-1");
        //组装菜单树
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<UserAuthorizeModel> data = JsonUtil.getJsonToList(trees, UserAuthorizeModel.class);
        List<UserAuthorizeModel> dataList = new LinkedList<>();
        List<UserAuthorizeModel> appChildList = new LinkedList<>();
        for (UserAuthorizeModel model : data) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            UserAuthorizeModel appData = new UserAuthorizeModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
        }
        return dataList;
    }

    /**
     * 数据权限
     *
     * @param moduleList         功能
     * @param moduleResourceList 资源
     * @param authorizeLiat      权限集合
     * @return ignore
     */
    private List<UserAuthorizeModel> resourceData(List<ModuleModel> moduleList, List<ResourceModel> moduleResourceList, List<AuthorizeEntity> authorizeLiat, Map<String, ModuleModel> moduleMap) {
        List<AuthorizeModel> treeList = new ArrayList<>();
        List<String> moduleModeId = new ArrayList<>();
        //获取按钮的菜单id
        for (ResourceModel resourceModel : moduleResourceList) {
            moduleModeId.add(resourceModel.getModuleId());
            AuthorizeModel treeModel = new AuthorizeModel();
            treeModel.setId(resourceModel.getId());
            treeModel.setFullName(resourceModel.getFullName());
            treeModel.setParentId(resourceModel.getModuleId());
            treeModel.setIcon("fa fa-binoculars resource");
            treeList.add(treeModel);
        }
        List<ModuleModel> buttonList = moduleList.stream().filter(t -> moduleModeId.contains(t.getId())).collect(Collectors.toList());
        List<AuthorizeModel> moduleListAll = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(buttonList, moduleList), AuthorizeModel.class);
        treeList.addAll(moduleListAll);
        treeList = treeList.stream().sorted(Comparator.comparing(AuthorizeModel::getSortCode)).collect(Collectors.toList());
        List<SumTree<AuthorizeModel>> trees = TreeDotUtils.convertListToTreeDot(treeList, "-1");
        //组装菜单树
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<UserAuthorizeModel> data = JsonUtil.getJsonToList(trees, UserAuthorizeModel.class);
        List<UserAuthorizeModel> dataList = new LinkedList<>();
        List<UserAuthorizeModel> appChildList = new LinkedList<>();
        for (UserAuthorizeModel model : data) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            UserAuthorizeModel appData = new UserAuthorizeModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
        }
        return dataList;
    }

    @ApiOperation("设置主要组织、主要岗位（角色当前不做）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "majorType", value = "组织:Organize/岗位:Position/系统:System", dataType = "String"),
            @ApiImplicitParam(name = "majorId", value = "组织/岗位/系统id", dataType = "String")})
    @PutMapping("/major")
    public ActionResult<String> defaultOrganize(@RequestBody UserSettingForm userSettingForm){
        UserEntity userEntity = userService.getInfo(userProvider.get().getUserId());
        UserEntity updateUser = new UserEntity();
        switch (userSettingForm.getMajorType()){
            case PermissionConst.ORGANIZE:
                String orgId = userSettingForm.getMajorId();
                // 对角色权限进行验证
                if(!organizeRelationService.checkBasePermission(userEntity.getId(), orgId)){
                    return ActionResult.fail(MsgCode.FA025.get());
                }
                updateUser.setOrganizeId(orgId);
                // 岗位自动切换
                updateUser.setPositionId(organizeRelationService.autoGetMajorPositionId(userEntity.getId(), orgId, userEntity.getPortalId()));
                break;
            case PermissionConst.POSITION:
                updateUser.setPositionId(userSettingForm.getMajorId());
                break;
            case PermissionConst.SYSTEM:
                String type = "Web";
                if (userSettingForm.getMenuType() != null && userSettingForm.getMenuType() == 1) {
                    type = "App";
                }
                String finalType = type;
                List<ModuleModel> list = authorizeService.getAuthorize(true).getModuleList().stream().filter(t -> StringUtil.isNotEmpty(t.getSystemId()) && t.getSystemId().equals(userSettingForm.getMajorId()))
                        .filter(t -> finalType.equals(t.getCategory()))
                        .collect(Collectors.toList());
                if (list.size() == 0) {
                    return ActionResult.fail(MsgCode.FA027.get());
                }
                updateUser.setSystemId(userSettingForm.getMajorId());
                updateUser.setId(userEntity.getId());
                userService.updateById(updateUser);
                return ActionResult.success("切换成功");
            default:
                break;
        }
        updateUser.setId(userEntity.getId());
        userService.updateById(updateUser);
        return ActionResult.success(MsgCode.SU016.get());
    }

    @ApiOperation("获取当前用户所有组织")
    @GetMapping("/getUserOrganizes")
    public ActionResult<List<PermissionModel>> getUserOrganizes(){
        return ActionResult.success(userRelationService.getObjectVoList(PermissionConst.ORGANIZE));
    }

    @ApiOperation("获取当前用户当前组织底下所有岗位")
    @GetMapping("/getUserPositions")
    public ActionResult<List<PermissionModel>> getUserPositions(){
        return ActionResult.success(userRelationService.getObjectVoList(PermissionConst.POSITION));
    }


    @ApiOperation("获取当前用户所有角色")
    @GetMapping("/getUserRoles")
    public ActionResult<List<PermissionModel>> getUserRoles(){
        return ActionResult.success(userRelationService.getObjectVoList(PermissionConst.ROLE));
    }

    /*= different =*/

    /**
     * 修改app常用
     *
     * @param userAppDataForm
     * @return
     */
    @ApiOperation("修改app常用数据")
    @PutMapping("/SystemAppData")
    public ActionResult updateAppData(@RequestBody @Valid UserAppDataForm userAppDataForm) {
        UserInfo userInfo = userProvider.get();
        UserEntity entity = userService.getInfo(userInfo.getUserId());
        entity.setPropertyJson(userAppDataForm.getData());
        userService.updateById(entity);
        return ActionResult.success(MsgCode.SU016.get());
    }

}
